//
//  WBComposeView.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/5/7.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import pop

class WBComposeView: UIView {

    /// 添加按钮的滚动视图
    @IBOutlet weak var scrollView: UIScrollView!
    /// 返回按钮的x中心店的约束
    @IBOutlet weak var backBtnCenterXCons: NSLayoutConstraint!
    /// 关闭按钮的x中心的约束
    @IBOutlet weak var closeBtnCenterXCons: NSLayoutConstraint!
    
    @IBOutlet weak var backButton: UIButton!
    
    /// 如果当前的方法执行不了block.那就有一个全局的变量记录一下
    var completionCall: ((_ clsName: String?) -> ())?
    
    let buttonsInfo = [["imageName":"tabbar_compose_idea","title":"文字","clsName": "WBComposeVC"],
                       ["imageName":"tabbar_compose_photo","title":"照片/视频"],
                       ["imageName":"tabbar_compose_weibo","title":"长微博"],
                       ["imageName":"tabbar_compose_lbs","title":"签到"],
                       ["imageName":"tabbar_compose_review","title":"点评"],
                       ["imageName":"tabbar_compose_more","title":"更多","actionName":"clickMore"],
                       ["imageName":"tabbar_compose_friend","title":"好友圈"],
                       ["imageName":"tabbar_compose_wbcamera","title":"微博相机"],
                       ["imageName":"tabbar_compose_music","title":"音乐"],
                       ["imageName":"tabbar_compose_shooting","title":"拍摄"],
                       ]
    
    class func composeView() -> WBComposeView{
        
        let nib = UINib(nibName: "WBComposeView", bundle: nil)
        
        let composeView = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeView
        
        /// 设置撰写微博的frame,因为XIB创建的视图都是600 * 600
        composeView.frame = UIScreen.main.bounds
        
        composeView.setupUI()
        
        return composeView
    }

    func show(completionBlock:@escaping (_ clsName: String?) -> ()) {
        
        completionCall = completionBlock
        
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else{
            
            return
        }
        
        vc.view.addSubview(self)
        
        // 开始做动画效果
        addAnimationToView()
        
        addButtonsAnim()
    }
    
    
    @objc fileprivate func composeBtnClick(){
    
        print("点击了")
    
    }
    
    @IBAction func close(_ sender: UIButton) {
        
        addButtonsHiddenAnim()
    }
    
    @IBAction func backBtnClick(_ sender: UIButton) {
        
        //2:更改约束
        closeBtnCenterXCons.constant = 0
        backBtnCenterXCons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: { 
            
            self.layoutIfNeeded()
            self.backButton.alpha = 0
        }) { (_) in
            
            //1先让返回按钮显示
            self.backButton.isHidden = true
            self.backButton.alpha = 1
        }
        
        
        //3:滚动scrollView
        let offset = CGPoint(x: 0, y: 0)
        
        scrollView.setContentOffset(offset, animated: true)
    }
}

fileprivate extension WBComposeView{
    
    /// 给当前的视图添加一个alpha值的动画
    func addAnimationToView() {
        
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 0
        anim.toValue = 1
        
        anim.duration = 0.5
        
        pop_add(anim, forKey: nil)
    }
    
    /// 给按钮添加动画
    func addButtonsAnim() {
        
        let firstView = scrollView.subviews[0]
        
        for (i,btn) in firstView.subviews.enumerated() {
            
            let btnAnim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            btnAnim.fromValue = btn.center.y + 400
            btnAnim.toValue = btn.center.y
            
            
// MARK: - 和 springSpeed 联合使用
            btnAnim.springBounciness = 8   //弹性的系数
            btnAnim.springSpeed = 8         //弹性的速度
//          联合使用,对动画产生影响
            
            btnAnim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            btn.pop_add(btnAnim, forKey: nil)
        }
    }
    
    func addButtonsHiddenAnim(){
    
        //1:先判断是滚动视图的第几个view
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        let v = scrollView.subviews[page]
        
        for (i,btn) in v.subviews.reversed().enumerated() {
            
            let hiddenAnim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            hiddenAnim.fromValue = btn.center.y
            hiddenAnim.toValue = btn.center.y + 400
            
            hiddenAnim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            btn.pop_add(hiddenAnim, forKey: nil)
            
            print("第\(i)个")
            
            if i == (v.subviews.count - 1) {
                
                ///如果是最后一个的时候,给动画添加回调
                hiddenAnim.completionBlock = {(_ , _) in
                    
                    self.changeViewAlpha()
                }
            }
        }
    }
    
    /// 改变当前视图的alpha
    func changeViewAlpha(){
        
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 1
        anim.toValue = 0
        
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        
        anim.completionBlock = {( _ , _) in
            
            // 移除父视图
            self.removeFromSuperview()
        }
    }
}

fileprivate extension WBComposeView{
    
    func setupUI() {
        
        //1:强行更新scrollView
        layoutIfNeeded()
        
        let rect = scrollView.bounds
        
        for i in 0..<2 {
            
            //2:实例化view
            let v = UIView()
            
            v.clipsToBounds = false
            
            v.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            //3:想v中添加button
            addButtons(v: v, idx: i * 6)
            
            //4:想scrollView中添加v
            scrollView.addSubview(v)
        }
        
        //设置ScrollView的属性
        scrollView.contentSize = CGSize(width: rect.width * 2, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
    }
    
    /// 添加按钮
    func addButtons(v: UIView,idx: Int) {
        
        let count = (idx + 6)
        
        for i in idx..<count {
            
            /// 如果count大于按钮信息的字典数组,那么直接跳出循环
            if i >= buttonsInfo.count {
                
                break
            }
            
            let dict = buttonsInfo[i]
            
            guard let imageName = dict["imageName"],
                let title = dict["title"] else{
                    
                    continue
            }
            
            let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            ///利用反射机制,添加监听
            if let actionName = dict["actionName"] {
                
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else{
                
                btn.addTarget(self, action: #selector(otherBtnsClick(sender:)), for: .touchUpInside)
            }
            
            /// 给按钮的类名赋值
            btn.clsName = dict["clsName"]
            
            v.addSubview(btn)
        }
        
        let btnSize = CGSize(width: 100, height: 100)
        /// 两个按钮之间的间距
        let margin = (scrollView.bounds.width - 3 * btnSize.width) / 4
        
        for (i,btn) in v.subviews.enumerated() {
            
            let y: CGFloat = (i > 2) ? scrollView.bounds.height - btnSize.height : 0
            
            let col = i % 3
            
            let x: CGFloat = CGFloat(col + 1) * margin + CGFloat(col) * btnSize.width
            
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
        }
    }
    
    /// 点击其他按钮的监听方法
    @objc func otherBtnsClick(sender: WBComposeTypeButton){
    
        /// 先找到第几页
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i,btn) in v.subviews.enumerated() {
            
            let scaleAnim = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            let cale = sender == btn ? 1.5 : 0.5
            
            /// 结构体要转换成 id 必须要用NSValue包装一下
            let scale = NSValue(cgPoint: CGPoint(x: cale, y: cale))
            
            scaleAnim?.toValue = scale
            scaleAnim?.duration = 0.5
            
            btn.pop_add(scaleAnim, forKey: nil)
            
            /// 添加透明度的动画
            let alphaAnima: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            
            alphaAnima.toValue = 0.2
            alphaAnima.duration = 0.5
            
            btn.pop_add(alphaAnima, forKey: nil)
            
            
            /// 监听动画结束了
            if i == 0 {
                
                alphaAnima.completionBlock = { _ , _ in
                    
                    /// 需要model出来控制器了
                    print("动画结束了")
                    
                    self.completionCall?(sender.clsName)
                }
            }
        }
    }
    
    /// 点击更多按钮的监听方法
    @objc func clickMore()  {
        
        //点击了更多,让scrollView滚动一个屏幕的距离
        let offset = CGPoint(x: scrollView.bounds.width, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        
        //2:先让返回按钮显示
        backButton.isHidden = false
        
        //3:更改约束
        closeBtnCenterXCons.constant += 100
        backBtnCenterXCons.constant -= 100
        
        //4:添加一个动画
        UIView.animate(withDuration: 0.25) { 
            
            self.layoutIfNeeded()
        }
    }
}









